package com.lbs.demo.dao;


import com.lbs.demo.entities.UsersEntity;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class UserDao {

    public void addUser(UsersEntity user){
        Session session = MyDBConnection.getSession();
        Transaction transaction = session.beginTransaction();

        session.save(user);
        transaction.commit();
        session.close();
    }

    public List<UsersEntity> getAllUsers(){
        Session session = MyDBConnection.getSession();

        List<UsersEntity> usersList = session.createCriteria(UsersEntity.class).addOrder(Order.desc("id")).list();

        session.close();
        return usersList;
    }

    public UsersEntity findUser(String username,String password){

        Session session = MyDBConnection.getSession();

        Query query = session.createQuery("from UsersEntity u where u.name=:uname and u.password=:passwd");
        query.setParameter("uname",username);
        query.setParameter("passwd",password);

        List<UsersEntity> users = query.list();

        session.close();

        if(users.size()>0) return users.get(0);
        else return null;
    }
}
